﻿using Arch.EntityFrameworkCore.UnitOfWork;
using AutoMapper;
using MyTodo.Api.Entities;
using MyTodo.Api.Services.Interfaces;
using MyTodo.Shared.Dtos;
using MyTodo.Shared.Services;

namespace MyTodo.Api.Services;

public class LoginService : ILoginService
{
    private readonly IUnitOfWork _work;
    private readonly IMapper _mapper;

    public LoginService(IUnitOfWork work, IMapper mapper)
    {
        _work = work;
        _mapper = mapper;
    }

    public async Task<ApiResponse> LoginAsync(string account, string password)
    {
        try
        {
            var user = await _work.GetRepository<User>().GetFirstOrDefaultAsync(
                predicate: x => x.Account.Equals(account) &&
                x.Password.Equals(password));
            if (user == null)
            {
                return new ApiResponse("账号或者密码错误！");
            }
            return new ApiResponse(true, user);
        }
        catch (Exception ex)
        {
            return new ApiResponse($"登录失败！错误信息:{ex.Message}");
        }
    }

    public async Task<ApiResponse> RegisterAsync(UserDto user)
    {
        try
        {
            var dbUser = _mapper.Map<User>(user);
            var repository = _work.GetRepository<User>();
            var response = await repository.GetFirstOrDefaultAsync(predicate: x => x.Account.Equals(dbUser.Account));
            if (response != null)
            {
                return new ApiResponse("该账号已存在！");
            }
            dbUser.CreateDate = DateTime.Now;
            await repository.InsertAsync(dbUser);
            if (await _work.SaveChangesAsync() > 0)
            {
                return new ApiResponse("注册成功！", true);
            }
            return new ApiResponse("注册用户出现异常！");
        }
        catch (Exception ex)
        {
            return new ApiResponse($"注册失败！错误信息:{ex.Message}");
        }
    }
}
